#pragma once
#include <iostream>
#include <semaphore.h>
#include <pthread.h>
#include <mutex>
#include <vector>
#include <unistd.h>
#include "mutex.hpp"
using namespace std;
#define NUM 5
template <class T>
class proCost
{
public:
    proCost(int num = NUM) : _num(num), _p_i(0), _c_i(0)
    {
        pthread_mutex_init(&_mtx, nullptr);
        _v.resize(_num);
        sem_init(&_pro, 0, _num);
        sem_init(&_cost, 0, 0);
        cout << "信号量初始化完毕" << endl;
    }
    void push(const T &val)
    {
        sem_wait(&_pro);
        // sleep(100);
        myMtuex myMtx(_mtx);
        // sleep(100);
        _v[_p_i++] = val;
        _p_i %= _num;
        cout << "我是线程" << pthread_self() << " "
             << "已生产成功" << endl;
        sleep(1);
        sem_post(&_cost);
        // sleep(1);
    }
    void pop(T &x)
    {
        sem_wait(&_cost);
        // sleep(1);
        myMtuex myMtx(_mtx);
        x = _v[_c_i++];
        _c_i %= _num;
        cout << "我是线程" << pthread_self() << " "
             << "已消费成功" << x << endl;
        sleep(1);
        sem_post(&_pro);
    }
    ~proCost()
    {
        sem_destroy(&_pro);
        sem_destroy(&_cost);
        cout << "资源回收完毕" << endl;
    }

private:
    sem_t _pro;
    sem_t _cost;
    vector<T> _v;
    int _num;
    int _p_i;
    int _c_i;
    pthread_mutex_t _mtx;
};